/**
 * ================================
 * @author mohanlan
 * @description weapp storage utils
 * @version v0.1.0
 * ================================
 */

/**
 * Set storge asynchronous
 * 
 * @param key string key
 * @param data string data
 */
function set(key, data) {
  wx.setStorage({
    key: key,
    data: data
  })
}

/**
 * Set storge synchronous
 * 
 * @param key string key
 * @param data string data
 * @param success function to call when set storage success
 * @param fail function to call when set storage faild
 */
function setSync(key, data, success, fail) {
  try {
    wx.setStorageSync(key, data)
    typeof success == 'function' && success();
  } catch (e) {
    console.log("storageUtil.js - set storage sync faild with key [" + key + "] value[" + data + "]")
    typeof fail == 'function' && fail();
  }
}

/**
 * get storge asynchronous
 * 
 * @param key string key
 * @param success function to call when get storage success
 */
function get(key, success) {
  wx.getStorage({
    key: key,
    success: function (res) {
      console.log("storageUtil.js")
      console.log(res.data)
      typeof success == 'function' && success(res);
    }
  })
}

/**
 * get storge synchronous
 * 
 * @param key string key
 * @param success function to call when get storage success
 * @param fail function to call when get storage faild
 */
function getSync(key, success, fail) {
  try {
    var value = wx.getStorageSync(key)
    if (value) {
      typeof success == 'function' && success(value);
    } else {
      console.log("storageUtil.js - get empty storage value with key[" + key + "]")
      typeof fail == 'function' && fail();
    }
  } catch (e) {
    console.log("storageUtil.js - get storage faild with key[" + key + "]")
    typeof fail == 'function' && fail();
  }

}

function remove(key) {
  wx.removeStorage({
    key: key,
    success: function (res, success) {
      typeof success == 'function' && success(res);
    }
  })
}

function removeSync(key, success, fail) {
  try {
    wx.removeStorageSync(key)
    typeof success == 'function' && success();
  } catch (e) {
    console.log("storageUtil.js - remove storage" + key + " faild")
    typeof fail == 'function' && fail();
  }
}

/**
 * clear storge asynchronous
 */
function clear() {
  wx.clearStorage();
}

/**
 * clear storge synchronous
 * 
 * @param success function to call when clear storage success
 * @param fail function to call when clear storage faild
 */
function clearSync(success, fail) {
  try {
    wx.clearStorageSync()
    typeof success == 'function' && success();
  } catch (e) {
    console.log("storageUtil.js - clear storage faild")
    typeof fail == 'function' && fail();
  }
}

// exports method mapper
module.exports = {
  get: get,
  getSync: getSync,
  set: set,
  setSync: setSync,
  clear: clear,
  clearSync: clearSync,
  remove: remove,
  removeSync: removeSync
}